﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using System.Text;
using System.Linq.Expressions;
using Xiezl.Common.Repositorys;
using Xiezl.Common.EFExpressions;


namespace Xiezl.Common.Web.Controllers
{
    [HandleError]
    public class BaseController : Controller
    {
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);
            ViewData["Controller"] = requestContext.RouteData.Values["controller"].ToString();
            ViewData["Action"] = requestContext.RouteData.Values["action"].ToString();

        }

        protected int PageSize = 10;
        /// <summary>
        /// 将对象格式化Jqgrid格式数据
        /// </summary>
        /// <param name="o"></param>
        /// <param name="recordCount"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public string JsonForJqgrid(object o, int recordCount, int pageSize, int pageIndex)
        {

            // string str = JavaScriptConvert.SerializeObject(o);

            //上面的解决方案 如果o中属性有循环引用 会出现  Self referencing loop 异常
            JsonSerializerSettings setting = new JsonSerializerSettings();
            setting.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //主要是这一句            
            string str = JavaScriptConvert.SerializeObject(o, Formatting.None, setting);


            int num = Convert.ToInt32(Math.Ceiling((decimal)(Convert.ToDecimal(recordCount) / Convert.ToDecimal(pageSize))));
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            sb.Append(string.Concat(new object[] { "total:", num, ",page:", pageIndex + 1, ",records:", recordCount, ",rows:" }));
            sb.Append(str);
            sb.Append("}");
            return sb.ToString();
        }
        /// <summary>
        /// 将对象转化为Json字符串
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public string JsonObject(object o)
        {
            return JavaScriptConvert.SerializeObject(o);
        }
        /// <summary>
        /// 反序列化Json字符串为对应的对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public T GetObjectOfJson<T>(string json) where T : class
        {
            return JavaScriptConvert.DeserializeObject(json, typeof(T)) as T;
        }
        /// <summary>
        /// 生成查询页面弹出框信息json数据
        /// </summary>
        /// <param name="alertMessage"></param>
        /// <returns></returns>
        public string GetAlertMessageJson(string alertMessage)
        {
            string useData = "{total:0,page:1,records:0,userdata:{Message:\"" + alertMessage + "\"},rows:[]}";
            return useData;
        }
     

        /// <summary>
        /// 删除Session基础资料中数据
        /// </summary>
        /// <param name="sessionName"></param>
        public void ClearBSCSessionData(string sessionName)
        {
            if (Session != null)
            {
                Session[sessionName] = null;
            }
        }

        /// <summary>
        /// 获取页面分页查询条件
        /// </summary>
        /// <typeparam name="TEntity">待查询的实体</typeparam>
        /// <typeparam name="TPgQueryExp">页面查询转化类型</typeparam>
        /// <returns></returns>
        protected EFQueryParam<TEntity> GetQueryParam<TEntity, TPgQueryExp>()
            where TEntity : class
            where TPgQueryExp : class, IEFQueryExpression<TEntity>, new()
        {
            string sidx = "Code";
            if (!string.IsNullOrEmpty(Request.QueryString["sidx"]))
            {
                sidx = Request.QueryString["sidx"].ToString();
            }
            bool isSordAsc = false;
            if (!string.IsNullOrEmpty(Request.QueryString["sord"]))
            {
                if (Request.QueryString["sord"].ToString() == "asc")
                {
                    isSordAsc = true;
                }
            }
            int pageSize = System.Convert.ToInt32(Request.QueryString["rows"]);
            int pageIndex = System.Convert.ToInt32(Request.QueryString["page"]) - 1;

            IEFQueryExpression<TEntity> exp = null;
            if (!string.IsNullOrEmpty(Request["d"]))
            {
                try
                {
                    //此处的d为前台查询条件(json格式)
                    exp = GetObjectOfJson<TPgQueryExp>(Microsoft.JScript.GlobalObject.unescape(Request["d"]));
                }
                catch
                { }
            }
            if (exp == null)
                exp = new TPgQueryExp();

            EFQueryParam<TEntity> ret = new EFQueryParam<TEntity>(exp, sidx, isSordAsc, pageIndex, pageSize);
            return ret;
        }

    }
}
